package cn.csust.net2.manager.server.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.csust.net2.manager.server.security.AuthCurrentUser;
import cn.csust.net2.manager.server.service.impl.BaseServiceImpl;
import cn.csust.net2.manager.shared.po.User;
import cn.csust.net2.manager.shared.util.Utils;

public class UploadPhoto extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3907176325780019288L;
	
	private String[] image  = {"jpg", "png", "gif", "bmp"};

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
	//	WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		User user = (User)req.getSession().getAttribute(BaseServiceImpl.USER_SYS);
		AuthCurrentUser.set(user);
		try {
			List<FileItem> items = upload.parseRequest(req);
			for (final FileItem item : items) {
				if (!item.isFormField()) {
					String fileName = item.getName();
					String fileSuffix = Utils.getSuffix(fileName);
					if(isImageFile(fileSuffix)) {
						fileName = "";
						fileName =String.valueOf(user.getUserID() );
						String  filePath=this.getServletConfig().getServletContext().getRealPath("/");
						item.write(new File(filePath+"\\files\\userHead\\", fileName));
						resp.getWriter().write(fileName);
					} else {
						return ;
					}
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据上传文件的后缀判断改文件是否是图片文件
	 * @param fileStuffix
	 * @return
	 */
	private boolean isImageFile(String fileStuffix) {
		String stuffix = fileStuffix.toLowerCase();
		for(int i=0; i<image.length; i++) {
			if(stuffix.equals(image[i])) {
				return true;
			}
		}
		return false;
	}


}
